import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/topic_detail_list_view_controller.dart';
import '../model/topic_detail_model.dart';

class VideoTopicDetailController extends GetxController {
  final int id = Get.arguments["id"];

  var isLoadingData = true.obs;
  late TopicDetailModel topicDetailModel;
  var currentPlayingIndex = 0.obs;
  final List<GlobalKey> itemKeys = [];

  @override
  void onInit() {
    super.onInit();
    loadData();
  }

  void loadData() async {
    try {
      Dio dio = Dio();
      final url = "http://baobab.kaiyanapp.com/api/v3/lightTopics/internal/$id";
      print("url=$url");
      final response = await dio.get(url);
      var model = TopicDetailModel.fromJson(response.data);

      isLoadingData.value = false;
      topicDetailModel = model;
      itemKeys.addAll(List.generate(model.itemList!.length, (index) => GlobalKey()));
    } catch (e) {
      print("Error loading data: $e");
      isLoadingData.value = false;
    }
  }

  void stopPlay() {
    final id = topicDetailModel.itemList![currentPlayingIndex.value].id ?? 0;
    final vc = Get.find<TopicDetailListViewController>(tag: id.toString());
    vc.stopVideo();
  }

  void playVideo(int index) {

    stopPlay();

    final id = topicDetailModel.itemList![index].id ?? 0;
    final vc = Get.find<TopicDetailListViewController>(tag: id.toString());
    vc.playVideo();

    currentPlayingIndex.value = index;
  }
}